package net.sf.jimex.project;

import net.sf.jimex.project.util.Item;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * andrew 23.01.2006 21:53:01
 */
public class Task extends Item {
    private String assignee;
    private static final String DESCRIPTION = "description";
    private static final String NAME = "name";
    private static final String UPPERCASE_NAME = "Name";
    private static final String ESTIMATED = "estimated";
    private static final Pattern PROJECT_TIME_PATTERN = Pattern.compile("PT(\\d*)H(\\d*)M(\\d*)S");

    public Task() {
        super();
    }

    public String getName() {
        return getNameFromPropertis();
    }

    public String getNameFromPropertis() {
        String property = getProperty(UPPERCASE_NAME);
        if (property == null || "".equals(property)) {
            property = getProperty(NAME);
        }
        return property;
    }

    public void addChild(Task parentTask) {
        tasks.add(parentTask);
    }

    public List getSubTasks() {
        return tasks;
    }

    public String getAssignee() {
        return assignee;
    }

    public void setAssignee(String assignee) {
        this.assignee = assignee;
    }

    public String getDescription() {
        return getProperty(DESCRIPTION);
    }

    public String getEstimated() {
        return convertProjectTimeToMinutes(getProperty(ESTIMATED));
    }

    public static String convertProjectTimeToMinutes(String ptTime) {
        Matcher matcher = PROJECT_TIME_PATTERN.matcher(ptTime);
        long timeInSeconds = 0;
        if (matcher.matches()) {
            String hoursString = matcher.group(1);
            String minutesString = matcher.group(2);
            int hours = Integer.parseInt(hoursString);
            int minutes = Integer.parseInt(minutesString);
            timeInSeconds = hours * 60 + minutes;
        }
        return String.valueOf(timeInSeconds*60);
    }

    public boolean hasSubTasks() {
        List subTasks = getSubTasks();
        if (subTasks == null) {
            return false;
        }
        return subTasks.size() > 0;
    }
}
